package it.agm.fanta.asynctask.jersey.patch;

import it.agm.activity.dialog.GenericDialog;
import it.agm.fanta.FantaserviceApp;
import it.agm.fanta.R;
import it.agm.fanta.constants.Constants;
import android.app.ProgressDialog;
import android.os.AsyncTask;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class PostTask extends AsyncTask<String, String, String> {
	 
	  private final String url;
	  private final String requestBody;
	  private final Callback<String> callback;
	  protected ProgressDialog progress;
	  
	  PostTask(String url, String requestBody, Callback<String> callback) {
	    this.url = url;
	    this.requestBody = requestBody;
	    this.callback = callback;
	  }
	 
	  @Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			progress = new ProgressDialog(FantaserviceApp.currentActivity());
//			progress.setMessage(App.getAppContext().getResources().getString("..");
			
			progress.show();
			progress.setContentView(R.layout.action_progressbar);

		}
	  @Override
	  protected String doInBackground(String... params) {
	    final Client client = Client.create();
	    final WebResource resource = client.resource(url);
	    final Gson gson = new GsonBuilder().create();
	     ClientResponse response = null;
	    if(url.contains(Constants.SERVICE_WRITE_FORMAZIONE)){
	    	response = 	resource.type(MIMETypes.APPLICATION_JSON.getName()).post(ClientResponse.class,gson.toJson(FantaserviceApp.requestSetFormazione));
	    }else{
	    	response = resource.type(MIMETypes.APPLICATION_JSON.getName()).post(ClientResponse.class,gson.toJson(FantaserviceApp.request));
	    }
	    
	    if (response.getStatus() != 201 && response.getStatus() != 200) {
	    	final String respCode = ""+ response.getStatus();
	    	FantaserviceApp.currentActivity().runOnUiThread(new Runnable(){
	            public void run() {
	            	String service = url.substring(url.indexOf("json/") + 5);
	            	new GenericDialog(FantaserviceApp.currentActivity(), "Errore connessione : " + respCode +"\nEseguendo " + service,"ERROR");
	             }
	    	});
	    }
	    final String responseEntity = response.getEntity(String.class).replaceAll("\\\\", "");
	    
	    return responseEntity;//.substring(1, responseEntity.length() - 1);
	  }
	 
	  @Override
	  protected void onPostExecute(String result) {
		 callback.callback(result);
		 progress.hide();
	     super.onPostExecute(result);
	  }
	}